{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "import time\n",
    "import os\n",
    "from selenium import webdriver\n",
    "from selenium.webdriver.common.by import By\n",
    "from selenium.webdriver.chrome.options import Options\n",
    "\n",
    "# 浏览器设置\n",
    "options = Options()\n",
    "options.headless = False  # 关闭无头模式，避免被检测\n",
    "driver = webdriver.Chrome(options=options)\n",
    "\n",
    "# Pixiv 主页\n",
    "pixiv_url = \"https://www.pixiv.net/\"\n",
    "\n",
    "# **1. 加载 cookies**\n",
    "def load_cookies():\n",
    "    if os.path.exists(\"cookies.pkl\"):\n",
    "        driver.get(pixiv_url)\n",
    "        time.sleep(3)  # 等待页面加载\n",
    "        with open(\"cookies.pkl\", \"rb\") as f:\n",
    "            cookies = pickle.load(f)\n",
    "            for cookie in cookies:\n",
    "                driver.add_cookie(cookie)\n",
    "        print(\"✅ Cookies 加载成功！\")\n",
    "        driver.refresh()  # 刷新页面，使 cookies 生效\n",
    "        time.sleep(5)\n",
    "        return True\n",
    "    return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Cookies 加载成功！\n",
      "✅ 已使用 Cookies 登录，无需手动输入密码！\n",
      "🎉 已成功进入 Pixiv！\n"
     ]
    }
   ],
   "source": [
    "# **2. 登录并保存 cookies**\n",
    "def login_and_save_cookies():\n",
    "    driver.get(\"https://accounts.pixiv.net/login\")\n",
    "    print(\"🔑 请手动登录 Pixiv...\")\n",
    "    time.sleep(30)  # 给用户足够时间登录\n",
    "\n",
    "    # 登录后，保存 cookies\n",
    "    cookies = driver.get_cookies()\n",
    "    print(cookies)\n",
    "    with open(\"cookies.pkl\", \"wb\") as f:\n",
    "        pickle.dump(cookies, f)\n",
    "    print(\"✅ 登录成功，Cookies 已保存！\")\n",
    "\n",
    "# **3. 主运行逻辑**\n",
    "if not load_cookies():\n",
    "    login_and_save_cookies()\n",
    "else:\n",
    "    print(\"✅ 已使用 Cookies 登录，无需手动输入密码！\")\n",
    "\n",
    "# **4. 爬取 Pixiv 页面**\n",
    "driver.get(pixiv_url)\n",
    "time.sleep(5)\n",
    "print(\"🎉 已成功进入 Pixiv！\")\n",
    "\n",
    "# 关闭浏览器\n",
    "driver.quit()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
